package com.ph.finder.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineHyperlink;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.ph.finder.client.CityItem;
import com.ph.finder.client.CitySuggestOracle;
import com.ph.finder.client.PrecinctInfo;
import com.ph.finder.client.PrecinctService;
import com.ph.finder.client.PrecinctServiceAsync;
import com.ph.finder.client.Util;

public class LandingPage extends Composite {

	private static LandingPageUiBinder uiBinder = GWT
			.create(LandingPageUiBinder.class);

	interface LandingPageUiBinder extends UiBinder<Widget, LandingPage> {
	}

	@UiField(provided = true)
	SuggestBox city;

	@UiField
	TextBox precinctNo;

	@UiField
	InlineHyperlink findPrecinct;

	@UiField
	Label errorLabel;

	@UiField
	InlineLabel loadingLabel;

	@UiField
	Image spinnerImage;

//	@UiField
//	Button precinctSearch;
//
//	@UiField
//	Label error;

	private CityItem selection;

	private final MainShell ctr;

	private boolean findInProgress;

	public LandingPage(MainShell mainShell) {
		this.ctr = mainShell;
		city = new SuggestBox(new CitySuggestOracle());
		initWidget(uiBinder.createAndBindUi(this));

		// Area Handlers
		city.addSelectionHandler(new SelectionHandler<Suggestion>() {
			@Override
			public void onSelection(SelectionEvent<Suggestion> event) {
				selection = (CityItem) event.getSelectedItem();
			}
		});
		city.getTextBox().addChangeHandler(new ChangeHandler() {
			@Override
			public void onChange(ChangeEvent event) {
				if (selection != null &&
						!city.getTextBox().getText().equals(selection.getReplacementString())) {
					selection = null;
				}
			}
		});
		Util.track("/00-Start");
	}


	@UiHandler("findPrecinct")
	void onFindPrecinct(ClickEvent e) {
		if (selection == null) {
			UIUtils.error(errorLabel, "Please select a proper city or municipality.\nType a few letters and click on the city.");
			return;
		}
		String precinctNoStr = precinctNo.getText().trim().toUpperCase();
		if (precinctNoStr.length() != 0) {
				if (!precinctNoStr.matches("[0-9]+[a-zA-Z]*")) {
				UIUtils.error(errorLabel, "Invalid precinct number.\nIt should be something like '1009A'.");
				return;
			}
			while (precinctNoStr.length() < 5) {
				precinctNoStr = "0" + precinctNoStr;
			}
		} else {
			UIUtils.error(errorLabel, "Precinct Number is required.\nIt is in your Voter's ID.");
			return;
		}

		if (findInProgress) {
			return;
		}
		findInProgress = true;
		findPrecinct.addStyleName("disabled");
		spinnerImage.setVisible(true);
		loadingLabel.setText("Retrieving Precinct Information...");

		// Check if such data exists from data
		PrecinctServiceAsync service = (PrecinctServiceAsync) GWT.create(PrecinctService.class);
		service.getAllPrecinctInfo(selection,
				precinctNoStr,
				new AsyncCallback<PrecinctInfo>(){
					@Override
					public void onSuccess(PrecinctInfo result) {
						done();
						if (result == null) {
							UIUtils.error(errorLabel, "No Precinct found in that city/municipality.");
							return;
						}
						ctr.findPrecinct((PrecinctInfo) result);
					}
					@Override
					public void onFailure(Throwable caught) {
						done();
						UIUtils.error(errorLabel, "Searching Failed.  Please try again later.");
					}
					private void done() {
						findPrecinct.removeStyleName("disabled");
						findInProgress = false;
						spinnerImage.setVisible(false);
						loadingLabel.setText("");
					}
		});
	}

	@UiHandler("mapPrecinct")
	void onMapPrecinct(ClickEvent e) {
		ctr.mapPrecinct();
	}

	@UiHandler("mapPrecinctLearn")
	void onMapPrecinctLearn(ClickEvent e) {

	}

	@UiHandler("mapMakerLearn")
	void onMapMakertLearn(ClickEvent e) {

	}

}